package com.woniuxy.sales.controller;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.woniuxy.sales.common.RedisConst;
import com.woniuxy.sales.common.enumeration.BusinessCode;
import com.woniuxy.sales.common.enumeration.OrderStatus;
import com.woniuxy.sales.config.AlipayConfig;
import com.woniuxy.sales.mapper.ProductsOrdersMapper;
import com.woniuxy.sales.model.entity.ProductsOrders;
import com.woniuxy.sales.model.entity.ProductsOrdersDetails;
import com.woniuxy.sales.model.vo.OrderVo;
import com.woniuxy.sales.model.vo.PayRequest;
import com.woniuxy.sales.model.vo.ProductsOrderVo;
import com.woniuxy.sales.service.ProductsOrdersService;
import com.woniuxy.sales.untils.Assert;
import com.woniuxy.sales.untils.JwtTemplate;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/productsOrders")
@Slf4j
public class ProductsOrdersController {
    @Autowired
    private ProductsOrdersService productsOrdersService;
    @Autowired
    private JwtTemplate jwtTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AlipayConfig alipayConfig;
    @PostMapping("/addOrder")
    @ApiOperation("添加订单")
    public ResponseEntity<ProductsOrderVo> addOrder(@RequestHeader(name = "Authorization", required = false) String token,
                                                    @RequestBody ProductsOrderVo order) {
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        ProductsOrderVo car= productsOrdersService.addOrder(userId,order);
        log.info("车辆配置订单编号{}",car.getId());
        return ResponseEntity.ok(car);

    }

    @GetMapping("/loadAllOrders")
    @ApiOperation("查询指定状态的订单")
    public ResponseEntity<List<ProductsOrders>> loadOrdersByStatus(@RequestHeader(name = "Authorization", required = false) String token,
                                                                   Integer status) {
        // 从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));

        // 调用业务层查询订单
        List<ProductsOrders> orderVos = productsOrdersService.queryOrder(userId, status);

        if (orderVos == null || orderVos.isEmpty()) {
            // 返回空列表或者你可以返回一个自定义的错误信息
            return ResponseEntity.ok(Collections.emptyList()); // 返回一个空的列表
        }

        log.info("订单编号{}", orderVos.get(0).getId()); // 这里可以安全地访问第一个订单

        return ResponseEntity.ok(orderVos);
    }


    @PostMapping("/verifyCode")
    @ApiOperation("验证验证码")
    public ResponseEntity<String> verifyCode(@RequestBody Map<String, String> map) {
        String code = map.get("code");
        String telephone = map.get("telephone");
        //从Redis中获取验证码
        String codeKey = RedisConst.SHORT_MESSAGE_SERVICE + ":" + telephone;
        String smsCode = stringRedisTemplate.opsForValue().get(codeKey);
        //判断验证码是否过期 Objects.isNull(smsCode)
        Assert.error(!StringUtils.hasText(smsCode), BusinessCode.INVALID_VERIFICATION);
        //判断验证码是否正确
        Assert.error(!code.equals(smsCode), BusinessCode.INVALID_VERIFICATION);
        //删除验证码
        stringRedisTemplate.delete(codeKey);
        return ResponseEntity.ok("success");
    }

    @GetMapping("/orders")
    @ApiOperation("查询订单")
    public ResponseEntity<List<ProductsOrdersDetails>> queryOrders(@RequestHeader(name = "Authorization", required = false) String token,
                                                                   @RequestParam(name = "orderId") Long id) {
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        log.info("订单编号{}",id);
        List<ProductsOrdersDetails> order = productsOrdersService.queryOrders(userId ,id);
        return ResponseEntity.ok(order);
    }
    @ApiOperation("取消订单")
    @PostMapping("/cancel/{orderId}")
    public ResponseEntity<String> cancelOrder(
            @RequestHeader(name = "Authorization", required = false) String token,
            @PathVariable Long orderId) {
        // 从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));

        try {
            // 调用业务层取消订单
            productsOrdersService.cancelOrder(orderId, userId);
            return ResponseEntity.ok("订单已成功取消，订单号：" + orderId);
        } catch (RuntimeException e) {
            // 捕获可能发生的异常（例如订单不存在或不可取消的情况）
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    @PostMapping("/pay")
    @ApiOperation("支付接口")
    public ResponseEntity<String> pay(@RequestBody PayRequest request) {
        // 调用业务层支付，传递 uniqueCode
        String form = productsOrdersService.pay(Long.valueOf(request.getOrderId()), request.getUniqueCode());
        return ResponseEntity.ok(form);
    }


    /**
     * 支付宝异步回调接口
     * http://内网穿透地址/orders/notify
     */
    @PostMapping("/notify")
    @ApiOperation("支付回调")
    public void alipayNotify(HttpServletRequest request) throws AlipayApiException {
        //获取所有请求参数，重新创建一个Map再封装一次数据
        Map<String,String> params=request.getParameterMap().entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey,e->e.getValue()[0]));
        // 验证签名
        log.info("支付宝回调参数：{}", params);
        String sign = params.get("sign");
        String contentV1 = AlipaySignature.getSignCheckContentV1(params);
        boolean rsa256CheckSignature = AlipaySignature.rsa256CheckContent(contentV1,
                sign, alipayConfig.getAlipayPublicKey(), "UTF-8");
        //表示支付成功
        if (rsa256CheckSignature && "TRADE_SUCCESS".equals(params.get("trade_status"))) {
            // 签名验证成功 并且 支付宝回调的状态是成功状态 TRADE_SUCCESS
            log.info("在{}，买家{}进行订单{}的付款，交易名称{}，付款金额{}", params.get("gmt_payment"), params.get("buyer_id"),
                    params.get("out_trade_no"), params.get("subject"), params.get("total_amount"));

            // 支付成功，修改数据库中该订单的状态，out_trade_no即订单ID
            String outTradeNo = params.get("out_trade_no");
            //更新订单状态为待发货

            productsOrdersService.updateStatus(Long.valueOf(outTradeNo), OrderStatus.PAID.getCode());

            log.info("订单{}支付成功，状态修改为待发货", outTradeNo);
        } else {
            log.error("支付宝支付失败");
        }
    }


}
